package com.apes.fn.fico.expense.platformFee.process;

import com.apes.fn.fico.expense.platformFee.CommonFeeProcess;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.LogicalUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.voucher.model.Voucher;
import com.apes.scm.voucher.model.VoucherItem;
import com.apes.scm.voucher.repository.VoucherRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 业务凭证生成平台费用细项单据
 * 同一单据可能满足多种条件，无法走公共方法生成 CommonFeeProcess 中的 createExpense
 */
@Service
public class VoucherFeeProcess extends CommonFeeProcess {

    @Autowired
    private VoucherRepository voucherRepository;

    @Override
    public void process(SimpleRequest request) {
        String id = request.get("id");
        Voucher voucher = voucherRepository.findOne(id);
        createExpense(voucher);
    }

    /**
     * 平台服务费
     *
     * @param voucher
     */
    private void createExpense(Voucher voucher) {
        //品类减免平台服务费
        if (voucher.getVoucherItems().stream().mapToDouble(VoucherItem::getPlatformServiceFeeReduced).sum() != 0)
            createFeeReduced(voucher);
//        //同接入商销售减免平台服务费
//        if (voucher.getVoucherItems().stream().mapToDouble(VoucherItem::getPlatformInternalReduced).sum() != 0)
//            createInternalReduced(voucher);
        //委托定损减免平台服务费
        if (voucher.getVoucherItems().stream().mapToDouble(VoucherItem::getBasePlatformManagementFee).sum() != 0)
            createManagementFee(voucher);
        //供应商供应链管理费
        if (("SUPPLIER_PURCHASE".equals(voucher.getVoucherType()) && "IM_OWN".equals(voucher.getInventoryMode())) ||
                ("SUPPLIER_CONSUME".equals(voucher.getVoucherType()) && "IM_CONSIGN".equals(voucher.getInventoryMode())))
            createSupplierFee(voucher);
        //平台内客户
        if ("CUSTOMER_SALE".equals(voucher.getVoucherType()) &&
                "IM_OWN".equals(voucher.getInventoryMode()) &&
                !"CROSS_IC".equals(voucher.getClassification()) &&
                (LogicalUtil.notIn(voucher.getOriginBusinessType(), "RetailReturn", "ProfitAndLoss") ||
                        ("RetailReturn".equals(voucher.getOriginBusinessType()) &&
                                LogicalUtil.in(voucher.getClassification(), "08", "09"))) &&
                voucher.getCompany().getParty().getId() != voucher.getPartner().getParty().getId())
            createExpensePTNKH(voucher);
        //e服务
        if ("CUSTOMER_SALE".equals(voucher.getVoucherType()) &&
                !"ProfitAndLoss".equals(voucher.getOriginBusinessType()) &&
                voucher.getCompany().getParty().getId() != voucher.getPartner().getParty().getId())
            createExpenseEFW(voucher);
    }

    /**
     * 品类减免平台服务费
     *
     * @param voucher
     */
    private void createFeeReduced(Voucher voucher) {
        Map map = MapUtil.mapper("order", voucher.getId(), "orderType", "Voucher",
                "source", voucher.getOrigin(), "sourceBusinessType", voucher.getOriginBusinessType(),
                "summary", "", "incomeTypeId", "A09", "expenseDetailsTypeId", "002054","date",voucher.getCreateDate(),
                "paymentAmount", voucher.getVoucherItems().stream().mapToDouble(VoucherItem::getPriceTotal).sum() - voucher.getVoucherItems().stream().mapToDouble(VoucherItem::getDiscount).sum(),
                "expenseAmount", voucher.getVoucherItems().stream().mapToDouble(VoucherItem::getPlatformServiceFeeReduced).sum() * -1,
                "deptId", voucher.getDept().getId(), "companyId", voucher.getCompany().getId());
        createExpenseByFee(map);
    }

    /**
     * 同接入商销售减免平台服务费
     *
     * @param voucher
     */
    private void createInternalReduced(Voucher voucher) {
        Map map = MapUtil.mapper("order", voucher.getId(), "orderType", "Voucher",
                "source", voucher.getOrigin(), "sourceBusinessType", voucher.getOriginBusinessType(),
                "summary", "", "incomeTypeId", "A09", "expenseDetailsTypeId", "002049","date",voucher.getCreateDate(),
                "paymentAmount", voucher.getVoucherItems().stream().filter(voucherItem -> voucherItem.getPlatformServiceFeeReduced() != 0).mapToDouble(VoucherItem::getPriceTotal).sum() - voucher.getVoucherItems().stream().mapToDouble(VoucherItem::getDiscount).sum(),
                "expenseAmount", voucher.getVoucherItems().stream().mapToDouble(VoucherItem::getPlatformInternalReduced).sum() * -1,
                "deptId", voucher.getDept().getId(), "companyId", voucher.getCompany().getId());
        createExpenseByFee(map);
    }

    /**
     * 委托定损减免平台服务费
     *
     * @param voucher
     */
    private void createManagementFee(Voucher voucher) {
        Map map = MapUtil.mapper("order", voucher.getId(), "orderType", "Voucher",
                "source", voucher.getOrigin(), "sourceBusinessType", voucher.getOriginBusinessType(),
                "summary", "", "incomeTypeId", "A09", "expenseDetailsTypeId", "002047","date",voucher.getCreateDate(),
                "paymentAmount", voucher.getVoucherItems().stream().mapToDouble(VoucherItem::getTaxCostPrice).sum() + voucher.getVoucherItems().stream().mapToDouble(VoucherItem::getLossQuotationFee).sum(),
                "expenseAmount", voucher.getVoucherItems().stream().mapToDouble(VoucherItem::getBasePlatformManagementFee).sum() * -1,
                "deptId", voucher.getDept().getId(), "companyId", voucher.getCompany().getId());
        createExpenseByFee(map);
    }

    /**
     * 供应商供应链管理费
     *
     * @param voucher
     */
    private void createSupplierFee(Voucher voucher) {
        Map map = MapUtil.mapper("order", voucher.getId(), "orderType", "Voucher",
                "source", voucher.getOrigin(), "sourceBusinessType", voucher.getOriginBusinessType(),
                "summary", "", "incomeTypeId", "A21", "expenseDetailsTypeId", "002053","date",voucher.getCreateDate(),
                "paymentAmount", voucher.getVoucherItems().stream().mapToDouble(VoucherItem::getPriceTotal).sum(),
                "expenseAmount", voucher.getVoucherItems().stream().mapToDouble(VoucherItem::getSupplyChainManagementFee).sum(),
                "deptId", voucher.getDept().getId(), "companyId", voucher.getCompany().getId());
        createExpenseByFee(map);
    }

    /**
     * 平台内客户平台服务费
     *
     * @param voucher
     */
    private void createExpensePTNKH(Voucher voucher) {
        List<VoucherItem> voucherItemList = voucher.getVoucherItems().stream()
                .filter(voucherItem -> !"0002902284".equals(voucherItem.getProduct().getId()))
                .collect(Collectors.toList());
        if (voucherItemList.isEmpty()) return;
        Map map = MapUtil.mapper("order", voucher.getId(), "orderType", "Voucher",
                "source", voucher.getOrigin(), "sourceBusinessType", voucher.getOriginBusinessType(),
                "summary", "平台内客户", "incomeTypeId", "A09", "expenseDetailsTypeId", "002052","date",voucher.getCreateDate(),
                "paymentAmount", voucherItemList.stream().mapToDouble(VoucherItem::getPriceTotal).sum() - voucherItemList.stream().mapToDouble(VoucherItem::getDiscount).sum(),
                "expenseAmount", voucherItemList.stream().mapToDouble(VoucherItem::getPlatformManagementFee).sum(),
                "deptId", voucher.getDept().getId(), "companyId", voucher.getCompany().getId());
        createExpenseByFee(map);
    }

    /**
     * e服务平台服务费
     *
     * @param voucher
     */
    private void createExpenseEFW(Voucher voucher) {
        List<VoucherItem> voucherItemList = voucher.getVoucherItems().stream()
                .filter(voucherItem -> "0002902284".equals(voucherItem.getProduct().getId()))
                .collect(Collectors.toList());
        if (voucherItemList.isEmpty()) return;
        double priceTotal = voucherItemList.stream().mapToDouble(VoucherItem::getPriceTotal).sum();
        double platformFreeRatio = getPlatformFreeRatio(voucher.getCompany().getId());
        double expenseAmount = priceTotal * platformFreeRatio;
        Map map = MapUtil.mapper("order", voucher.getId(), "orderType", "Voucher",
                "source", voucher.getOrigin(), "sourceBusinessType", voucher.getOriginBusinessType(),
                "summary", "e服务", "incomeTypeId", "A09", "expenseDetailsTypeId", "002052","date",voucher.getCreateDate(),
                "paymentAmount", priceTotal - voucherItemList.stream().mapToDouble(VoucherItem::getDiscount).sum(), "expenseAmount", expenseAmount,
                "deptId", voucher.getDept().getId(), "companyId", voucher.getCompany().getId());
        createExpenseByFee(map);
    }

    @Override
    public Map<String, Object> getExpenseModel(Map map) {
        return null;
    }

    @Override
    public boolean support(String type) {
        return "Voucher".equals(type);
    }
}
